package io.github.novaframe.config;

import io.github.novaframe.async.ExceptionHandlingAsyncTaskExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executor;

/**
 * Created by Locki on 6/22/2017.
 */
@Configuration
@EnableAsync
@EnableScheduling
public class AsyncConfiguration implements AsyncConfigurer, SchedulingConfigurer {

    private final Logger logger = LoggerFactory.getLogger(AsyncConfiguration.class);

    private final NovaframeProperties properties;

    public AsyncConfiguration(NovaframeProperties properties) {
        this.properties = properties;
    }

    /**
     * 异步线程池
     * @return
     */
    @Bean(name = "taskExecutor")
    public ThreadPoolTaskExecutor getTaskExecutor() {
        logger.debug("create taskExecutor...");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(properties.getAsync().getCorePoolSize());
        executor.setMaxPoolSize(properties.getAsync().getMaxPoolSize());
        executor.setQueueCapacity(properties.getAsync().getQueueCapacity());
        executor.setThreadNamePrefix("Async-Thread-");
        return executor;
    }

    /**
     * 定时任务线程池
     * @return
     */
    @Bean(name = "taskScheduler")
    public ThreadPoolTaskScheduler getTaskScheduler() {
        logger.debug("create taskScheduler...");
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(10);
        scheduler.setThreadNamePrefix("Scheduled-Thread-");
        return scheduler;
    }

    @Override
    public Executor getAsyncExecutor() {
        return new ExceptionHandlingAsyncTaskExecutor(getTaskExecutor());
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new SimpleAsyncUncaughtExceptionHandler();
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.setScheduler(getTaskScheduler());
    }
}
